<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Double Spring</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Press and drag circles with mouse.</aside>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = utils.captureMouse(canvas),
          ball0 = new Ball(20),
          ball1 = new Ball(20),
          ball0_dragging = false,
          ball1_dragging = false,
          spring = 0.03,
          friction = 0.9,
          springLength = 100,
          vx = 0,
          vy = 0;

      ball0.x = Math.random() * canvas.width;
      ball0.y = Math.random() * canvas.height;

      ball1.x = Math.random() * canvas.width;
      ball1.y = Math.random() * canvas.height;

      canvas.addEventListener('mousedown', function () {
        if (utils.containsPoint(ball0.getBounds(), mouse.x, mouse.y)) {
          ball0_dragging = true;
        }
        if (utils.containsPoint(ball1.getBounds(), mouse.x, mouse.y)) {
          ball1_dragging = true;
        }
      }, false);

      canvas.addEventListener('mouseup', function () {
        if (ball0_dragging || ball1_dragging) {
          ball0_dragging = false;
          ball1_dragging = false;
        }
      }, false);

      canvas.addEventListener('mousemove', function () {
        if (ball0_dragging) {
          ball0.x = mouse.x;
          ball0.y = mouse.y;
        }
        if (ball1_dragging) {
          ball1.x = mouse.x;
          ball1.y = mouse.y;
        }
      }, false);

      function springTo (ballA, ballB) {
        var dx = ballB.x - ballA.x,
            dy = ballB.y - ballA.y,
            angle = Math.atan2(dy, dx),
            targetX = ballB.x - Math.cos(angle) * springLength,
            targetY = ballB.y - Math.sin(angle) * springLength;

        ballA.vx += (targetX - ballA.x) * spring;
        ballA.vy += (targetY - ballA.y) * spring;
        ballA.vx *= friction;
        ballA.vy *= friction;
        ballA.x += ballA.vx;
        ballA.y += ballA.vy;
      }

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        if (!ball0_dragging) {
          springTo(ball0, ball1);
        }
        if (!ball1_dragging) {
          springTo(ball1, ball0);
        }
        context.beginPath();
        context.moveTo(ball0.x, ball0.y);
        context.lineTo(ball1.x, ball1.y);
        context.stroke();
        ball0.draw(context);
        ball1.draw(context);
      }());
    };
    </script>
  </body>
</html>
